/**
 * Created by 小敏哥on 2017/3/6.
 */
import {
    USE_COUPON,
    ORDER_INFO,
    PAY_SCRIPT
} from "./actionsTypes"

import jsApi from '../utils/cx580.jsApi';

import comfirmOrderService from '../services/comfirmOrderService';
import {Toast} from 'antd-mobile';
import typeOfBrowser from '../utils/typeOfBrowser';
import SendCxytjMessage from '../utils/sendCxytjMessage';
import urlOperation from "../utils/urlOperation";
import appVersion from '../utils/appVersion';


export const useCoupon = data => ({type: USE_COUPON, data: data}); //使用优惠券
export const orderInfo = data => ({type: ORDER_INFO, data: data}); //用户订单信息
export const payScript = data => ({type: PAY_SCRIPT, data: data});


let checkOutCounterPay = (data, callBack) => {
    Toast.hide();
    Toast.loading("", 30, () => Toast.info("网络错误", 2));
    comfirmOrderService.orderPay(data).then(resultData => {
        Toast.hide();
        if (resultData.code == 1000) {
            if (callBack && resultData.data.resultFlag == '1') {
                callBack(resultData.data)
            }
            else {
                Toast.info('生成订单失败', 2);
            }
        }
        else {
            Toast.info(resultData.msg, 2);
        }
    });
};
//app支付
let appPay = (data, paySuccessCallBack) => {
    Toast.hide();
    Toast.loading("", 30, () => Toast.info("网络错误", 2));
    comfirmOrderService.appOrderPay(data).then(resultData => {
        Toast.hide();
        if (resultData.code == 1000) {
            if (resultData.data.resultFlag == '1') {
                var content = {
                    "commandId": "",
                    "command": "payOrder",
                    "data": {
                        "orderId": resultData.data.orderId,
                        "orderType": resultData.data.orderType,
                        "orderAmt": resultData.data.payAmount,
                        "payType": resultData.data.payAmount > 0 ? data.payType : '17',
                        "token": resultData.data.paySignToken
                    }
                };
                jsApi.call(content, function (result) {
                    if (result.data.tradeStatus == 1) {
                        paySuccessCallBack && paySuccessCallBack({
                            orderId: resultData.data.orderId,
                            orderType: resultData.data.orderType,
                            payType: data.payType,
                            payAmount: resultData.data.payAmount,
                        });
                    }
                    else {
                        let message = '';
                        switch (result.data.tradeStatus) {
                            case 2:
                                message = '支付失败';
                                break;
                            case 3:
                                message = '网络超时';
                                break;
                            case 4:
                                message = '用户信息登录超时';
                                break;
                            case 5:
                                message = '支付软件没安装或者不支持该支付';
                                break;
                        }
                        data.message && Toast.info(message, 2);
                    }
                });
            }
            else {
                Toast.info('生成订单失败', 2);
            }
        }
        else {
            Toast.info(resultData.msg, 2);
        }
    });
};


//获取订单信息
export const getOrderInfo = (data, callBack) => {
    return (dispatch, getState) => {
        Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        comfirmOrderService.getOrderInfo(data).then(resultData => {
            Toast.hide();
            if (resultData.code == 1000) {
                dispatch(orderInfo({
                    allDataForCoupon: JSON.stringify(resultData.data),//缓存所有数据用于优惠券列表数据获取
                    userName: resultData.data.userName,
                    userPhone: resultData.data.userPhone,
                    price: resultData.data.totalPoundage,//优惠前总金额
                    allDiscount: resultData.data.discountAmount,//优惠总金额
                    payAmount: resultData.data.payAmount,//优惠后金额
                    showVip: resultData.data.vip.showVip == '1',
                    isVip: resultData.data.vip.showVip == '1' && resultData.data.vip.isCheWuUser == '1',
                    discount: resultData.data.vip.discountFee,//vip卡优惠
                    priceOfVip: resultData.data.vip.vipCardAmount ? resultData.data.vip.vipCardAmount : 0,
                    chewuId: resultData.data.vip.chewuId,
                    showCoupon: resultData.data.coupon.showCoupon == '1',
                    couponCount: resultData.data.coupon.couponCount,
                    defaultCouponId: resultData.data.coupon.couponIds,
                    defaultCouponDiscount: resultData.data.coupon.couponDiscount,
                    inspectionType: resultData.data.extension.inspectionType,
                    driveType: data.driveType,
                    mailType: data.mailType,
                    activityTitle: resultData.data.activity.title,//活动标题
                    activityDiscount: resultData.data.activity.account,//活动折扣
                    mailTypeList: resultData.data.mailTypeList,
                    tips: resultData.data.tips,//年检方式/递寄方式Tips信息
                    regionData: resultData.data.regions,//车检地址信息
                    walletBalance: resultData.data.walletBalance,//用户app钱包余额
                    orderTip: resultData.data.orderTip,//顶部提示
                }));
                if (callBack) {
                    callBack();
                }
            }
            else {
                /*    alert(JSON.stringify(data));
                    alert(resultData.code);*/
                Toast.info(resultData.msg, 2);
            }
        });
    }
};


//支付订单接口
export const orderPay = (data) => {
    return (dispatch, getState) => {
        Toast.hide();
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        let userChannel = typeOfBrowser.getChannelOfBrowser();
        if (userChannel == 'aliPay' || userChannel == 'weixin' || userChannel == 'qq') {
            //收银台
            checkOutCounterPay(data, (result) => {
                /*alert(JSON.stringify(result));
                dispatch(payScript(result.paySign));*/
                //location.href='http://webtest.cx580.com:10002/Pay?TotalFee=0.01&Transmit=alipay&OutTradeNo=TEST02170512000231&NotifyUrl=http%3A%2F%2F192.168.1.165%3A7083%2Forder%2Fnotify&sign=B37957664161AF0482E11D9F1499285C&ReturnUrl=http%3A%2F%2F192.168.1.165%3A7083%2Finspection%2Findex.html%23%2ForderDetails%2F&Body=%E5%85%AD%E5%B9%B4%E5%86%85%E6%96%B0%E8%BD%A6%E5%B9%B4%E6%A3%80%E4%BB%A3%E5%8A%9E%E6%9C%8D%E5%8A%A1%28%E7%B2%A4F542212%29&Partner=db06c78d1e24cf708a14ce81c9b617ec&Subject=%E5%85%AD%E5%B9%B4%E5%86%85%E6%96%B0%E8%BD%A6%E5%B9%B4%E6%A3%80%E4%BB%A3%E5%8A%9E%E6%9C%8D%E5%8A%A1%28%E7%B2%A4F542212%29';
                //document.write(result.paySign); //跳转到收银台
                location.href = result.paySign;
            });
        }
        //app支付
        else if (userChannel == 'app') {
            appPay(data, (notificationData) => {
                SendCxytjMessage.sendMessage({eventId: data.inspectionType == '2' ? 'H5_E_Orderpage_PaySuccess' : 'H5_E_Orderpage_online_PaySuccess'});
                /*  var href = window.location.href.split('?')[0].replace('#/', '');
                  window.location.replace(`${href}#/orderDetails/?OutTradeNo=${notificationData.orderId}`);*/
                dispatch(payNotification(notificationData, (notifyResult) => {
                    if (notifyResult.data.resultFlag == '1') {
                        Toast.loading("正在查询支付状态", 2);
                        setTimeout(() => {
                            let urlOfNow = window.location.href;
                            let baseUrl = urlOfNow.replace(window.location.hash, '').split('?')[0].replace('#/', '');
                            //app端跳转到特殊处理页面，防止双标题
                            if (typeOfBrowser.getChannelOfBrowser() == 'app') {
                                //6.3之后app已解决此问题,新版本不使用兼容
                                if (appVersion.getMainVersionByCount()>6.32) {
                                    window.location.href = `${baseUrl}#/annualInspection/${notificationData.orderId}/shut`;
                                }
                                else {
                                    window.location.href = `${baseUrl}#/APPjumpUrl/${notificationData.orderId}`;
                                }
                            }
                            else {
                                window.location.replace(`${baseUrl}#/annualInspection/${notificationData.orderId}`);
                            }
                        }, 2000);
                    }
                    else {
                        if (notifyResult.msg) {
                            Toast.info(notifyResult.msg, 2);
                        }
                        //alert(resultData.msg);
                    }
                }))
            });
        }
        //其他情况默认收银台支付
        else {
            checkOutCounterPay(data, (result) => {
                /* dispatch(payScript(result.paySign));*/
                //location.href='http://webtest.cx580.com:10002/Pay?TotalFee=0.01&Transmit=alipay&OutTradeNo=TEST02170512000231&NotifyUrl=http%3A%2F%2F192.168.1.165%3A7083%2Forder%2Fnotify&sign=B37957664161AF0482E11D9F1499285C&ReturnUrl=http%3A%2F%2F192.168.1.165%3A7083%2Finspection%2Findex.html%23%2ForderDetails%2F&Body=%E5%85%AD%E5%B9%B4%E5%86%85%E6%96%B0%E8%BD%A6%E5%B9%B4%E6%A3%80%E4%BB%A3%E5%8A%9E%E6%9C%8D%E5%8A%A1%28%E7%B2%A4F542212%29&Partner=db06c78d1e24cf708a14ce81c9b617ec&Subject=%E5%85%AD%E5%B9%B4%E5%86%85%E6%96%B0%E8%BD%A6%E5%B9%B4%E6%A3%80%E4%BB%A3%E5%8A%9E%E6%9C%8D%E5%8A%A1%28%E7%B2%A4F542212%29';
                // document.write(result.paySign); //跳转到收银台
                location.href = result.paySign;
            });
        }

    }
};

//支付完成通知接口
const payNotification = (data, callBack) => {
    return (dispatch, getState) => {
        Toast.hide();
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        comfirmOrderService.payNotification(data).then(resultData => {
            Toast.hide();
            if (resultData.code == 1000) {
                callBack && callBack(resultData);
            }
            else {
                Toast.info(resultData.msg, 2);
            }
        });
    }
}


